package cn.jilian.meta.handler.generators;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;

import cn.jilian.entity.MField;
import cn.jilian.entity.Meta;
import cn.jilian.meta.handler.CompGenerator;
import cn.jilian.meta.handler.GeneratorManager;
import cn.jilian.meta.handler.domain.AbstractStore;
import cn.jilian.meta.handler.domain.Column;
import cn.jilian.meta.handler.domain.Grid;
import cn.jilian.meta.handler.domain.SimpleRestJsonStore;

public class SimpleGridGenerator implements CompGenerator<Grid> {
	
	private GeneratorManager manager ;
	
	public SimpleGridGenerator(GeneratorManager manager) {
		this.manager=manager;
	}
	
	@Override
	public Grid convert(Meta meta,Map<String,Object> extConfig) {
		Grid grid=new Grid();
		grid.setXtype("Ext.view."+meta.getCode());
		grid.setExtend("Ext.grid.Panel");
		grid.setName(meta.getCode());
		grid.setScrollable(Boolean.TRUE);
		grid.setSplit(Boolean.TRUE);
		if(extConfig!=null) {
			grid.setRegion((String) extConfig.get("region"));
		}
		Collection<Column> columns=new ArrayList<>();
		if(extConfig!=null) {
			if(extConfig.containsKey("showColumns")) {
				String showColumns=(String) extConfig.get("showColumns");
				String[] showColumnsArray=StringUtils.split(showColumns,",");
				for(MField f:meta.getFields()) {
					Column c=new Column();
					c.setText(f.getText());
					c.setDataIndex(f.getName());
					columns.add(c);
					Boolean flag=true;
					for(String col:showColumnsArray) {
						if(StringUtils.equalsIgnoreCase(c.getDataIndex(), col)) {
							flag=false;
						}
					}
					if(flag) {
						c.setHidden(true);
					}
				}
			}
		}else {
			for(MField f:meta.getFields()) {
				Column c=new Column();
				c.setText(f.getText());
				c.setDataIndex(f.getName());
				columns.add(c);
			}
		}
		CompGenerator<AbstractStore> storeGenerator=manager.getGenerator(SimpleRestJsonStore.class);
		AbstractStore store=storeGenerator.convert(meta, null);
		grid.setTitle(meta.getText()+"列表");
		grid.setStore(store);
		grid.setColumns(columns);
		Map<String,Object> pagingtoolabr=new HashMap<>();
		pagingtoolabr.put("xtype", "pagingtoolbar");
		pagingtoolabr.put("dock", "bottom");
		pagingtoolabr.put("displayInfo", true);
		pagingtoolabr.put("store", store);
		grid.setDockedItems(Collections.singleton(pagingtoolabr));
		return grid;
	}

	

}
